const _ = require('lodash');
const moment = require('moment');
const log = require('pino')({ level: 'info' });
const schedule = require('node-schedule');

const scheduleJob = function({ name, time, job }) {
  log.info(`启动定时任务: ${name}. ${time}`);

  const info = `执行定时任务: ${name}, ${time}`;
  schedule.scheduleJob(time, function(fireDate) {
    log.info(
      info +
        'This job was supposed to run at ' +
        moment(fireDate).format() +
        ', but actually ran at ' +
        moment().format()
    );

    if (_.isFunction(job)) {
      job();
    }
  });
};

const scheduleJobs = {
  perMinutes: function({ minutes, jobName }, job) {
    const time = `*/${minutes} * * * *`;
    const name = `【${jobName}】@ 每间【${minutes}分钟】`;
    scheduleJob({ time, name, job });
  },

  everyday: function({ hour, jobName }, job) {
    const time = `* * ${hour} * * *`;
    const name = `【${jobName}】@ 每天【${hour}点】`;
    scheduleJob({ time, name, job });
  },

  everySeconds: function({ second, jobName }, job) {
    const time = `*/${second} * * * * *`;
    const name = `【jobName】@ 每隔【${second}秒】`;
    scheduleJob({ time, name, job });
  },
};

module.exports = scheduleJobs;
